//引入文件系统
let fs = require('fs')

//获取假的用户信息
let user =  { username:"admin1",password:"12345" }

//读取person.json
let result = fs.readFileSync('./persons.json','utf-8')
// result 是一个字符串
// "[{"username":"xm1","password":"1234"},{"username":"xm2","password":"222"},{"username":"xm3","password":"333"}]"
//把字符串转化成为数组和对象
result = JSON.parse(result)
// findIndex
// console.log(result,'结果');
// result.findIndex(item=>{
//     return item.username === user.username && item.password ===user.password
// })
let index =result.findIndex(item=>item.username === user.username && item.password )
// console.log(index,'索引');
//根据索引去判断
if(index===-1){
    //新用户 追加
    result.push(user)
    console.log('注册成功');
}else {
    console.log('用户名已被注册');
}
//当注册成功，追加到文件中
result = JSON.stringify(result)
fs.writeFileSync('./persons.json',result)